package ar.com.photo_admin.domain

import ar.com.photo_admin.domain.order_state.*;

class PurchaseOrder extends DomainObject {
	
	PurchaseOrderState state
				
	List orderItems
	
	Photographer photographer
	
	User client
	
	Integer amountCopies;
	
	Float price;
	
	boolean paidOnline = false;
	
	MPOrderStatus MPstatus;
	
	String MPpaymentId
	
	static belongsTo = [photographer : Photographer, client: User]
	
	static hasMany = [orderItems : PurchaseOrderItem]
	
	static constraints = {
		state(nullable: false)
		MPstatus(nullable: true)
		MPpaymentId(nullable:true)
	}
	
	static mapping = {
		sort id:"desc"
	}
	
	PurchaseOrder(){
		state = new CreatedOrderState();		
	}
	
	def calculateAmountOfItems(){
		def acum = 0;
		
		orderItems.each {
			acum += it.amountCopies
		}
		
		amountCopies = acum;
	}
	
	def calculatePrice(){
		if( amountCopies== null)
			calculateAmountOfItems()
				
		price = amountCopies !=0 ? photographer.priceStrategy.calculatePrice(this) : 0; 
	}
	
	// STATES	
	def confirm(){
		state.confirm()
	}
	
	def approve(){
		state.approve()
	}
	
	def cancel(){
		state.cancel()
	}
	
	def refund(){
		state.refund();
	}
	
	def finish(){
		state.finalizeOrder();
	}	
	
	def isCancellable() {
		if (paidOnline) {
			// Regla de Mercado Pago
			return MPstatus == MPOrderStatus.PENDING || MPstatus == MPOrderStatus.IN_PROCESS ||MPstatus == MPOrderStatus.REJECTED || MPstatus == MPOrderStatus.IN_MEDIATION
		}
		else {
			state.isCancellable()
		}
	}
	
	def isFinalizable(){
		return state.isFinalizable();
	}
	
	def isRegistered(){
		return state.isRegistered()
	}
	
	def isRefundable(currentStatus) {
		// TODO sacar estados de MercadoPago (?)
		if (paidOnline) {
			return MPstatus == MPOrderStatus.APPROVED
		}
		else {
			return state.isRefundable()
		}
					
	}
	
	def updateStatusFromMPStringStatus(mpStringStatus){
		this.MPstatus = MPOrderStatus.getStatusFromString(mpStringStatus);
		switch (MPstatus) {
			case MPstatus.APPROVED:
				this.state.approve()
				break
			case MPstatus.CANCELLED:
				this.state.cancel()
				break
			case MPstatus.IN_MEDIATION:
				this.state.dispute()
				break
			case MPstatus.IN_PROCESS:
				this.state.inProcess()
				break
			case MPstatus.PENDING:
				this.state.pending()
				break
			case MPstatus.REFUNDED:
				this.state.refund()
				break
			case MPstatus.REJECTED:
				this.state.reject()
				break		
		}
	}
}
